import 'dart:async';
import 'dart:convert';
import 'dart:math';

import 'package:bike_ride/api/req.dart';
import 'package:bike_ride/common/mvvm/base_page.dart';
import 'package:bike_ride/common/util/account_manager.dart';
import 'package:bike_ride/common/util/extension.dart';
import 'package:bike_ride/common/util/format.dart';
import 'package:bike_ride/common/util/google_map_utils.dart';
import 'package:bike_ride/common/util/hysize_fit.dart';
import 'package:bike_ride/common/widget/circle_button_widget.dart';
import 'package:bike_ride/common/widget/dialog/mydialog.dart';
import 'package:bike_ride/common/widget/dialog/return_bike_failed_dialog.dart';
import 'package:bike_ride/common/widget/xb_button.dart';
import 'package:bike_ride/generated/l10n.dart';
import 'package:bike_ride/model/cyling/model/unpay_info_m.dart';
import 'package:bike_ride/model/cyling/view_model/cyling_vm.dart';
import 'package:bike_ride/model/main/model/area_info_m.dart';
import 'package:bike_ride/model/pay/view/pay_box_v.dart';
import 'package:bike_ride/model/unlock/model/bike_info_m.dart';
import 'package:bike_ride/res/style/color_styles.dart';
import 'package:bike_ride/res/style/text_styles.dart';
import 'package:bike_ride/res/style/theme_styles.dart';
import 'package:bike_ride/router/navigator_util.dart';
import 'package:bike_ride/router/routers.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:intl/intl.dart';

/// 解锁后 骑行中页面
class CyclingView extends BaseStatefulPage<CyclingViewModel> {
  ///vid,order_id
  final Map<String, dynamic> arguments;

  const CyclingView({required this.arguments, super.key});

  @override
  CyclingViewState createState() => CyclingViewState();
}

class CyclingViewState
    extends BaseStatefulPageState<CyclingView, CyclingViewModel> {
  final infoKey = GlobalKey<_BottomStackWidgetState>();

  @override
  void initAttribute() {}

  @override
  void initObserver() {}

  @override
  CyclingViewModel viewBindingViewModel() {
    return CyclingViewModel()
      ..viewState = this;
  }

  void notifyChange() {
    if (mounted) {
      setState(() {});
    }
  }

  void showBackFailedDialog(){
    showCupertinoModalPopup(
        context: context, builder: (context) =>IrregularStopMode(viewModel: viewModel!,)
    );
  }

  void showBacFeeDialog(Properties properties,int actionType,ReturnBikeReq req) async{
    await showCupertinoModalPopup(
      context: context,
      builder: (context) => PayBoxView(arguments: {
        'order_id': viewModel!.orderId,
        'action_type': actionType,
        'return_bike_req': req,
        'un_pay': UnPayInfoM(
            orderId: viewModel!.orderId,
            amount: properties.totalFee,
            costPrice: properties.totalFee,
            exceedPrice: properties.payByTime,
            properties: properties),
      }),
    );
    Future.delayed(const Duration(milliseconds: 500),()=>viewModel!.getOrderNoExist());
  }

  void navigatorToPay() async {
    infoKey.currentState?.cancelTimer();
    NavigatorUtil.push(context, Routers.payView,replace: true,arguments: {'order_id':viewModel!.orderId!}).then((value) {
      NavigatorUtil.back(context,toRoot: true);
    });
  }

  Future startLocation() async {
    GoogleMapUtils.getCurrentPosition((position)async{
      final kGooglePlex = CameraPosition(
        target: LatLng(position.latitude, position.longitude),
        zoom: max(viewModel!.mapZoom, 18),
      );

      final GoogleMapController controller =
          await viewModel!.mapController.future;
      await controller
          .animateCamera(CameraUpdate.newCameraPosition(kGooglePlex));
    });
  }

  @override
  Widget appBuild(BuildContext context) {
    return Scaffold(
        extendBodyBehindAppBar: true,
        body: Stack(
          children: [
            GoogleMap(
              initialCameraPosition: CameraPosition(
                target: LatLng(AccountManager.userLatitude!.toDouble(),
                    AccountManager.userLongitude!.toDouble()),
                zoom: viewModel!.mapZoom,
              ),
              myLocationEnabled: true,
              trafficEnabled: true,
              zoomControlsEnabled: false,
              myLocationButtonEnabled: false,
              markers: <Marker>{
                ...viewModel!.stationMarkers,
                ...viewModel!.markers
              },
              polygons: <Polygon>{
                ...viewModel!.stationPolygons,
                ...viewModel!.areaPolygons
              },
              polylines: viewModel!.polyLines,
              onMapCreated: (GoogleMapController controller) {
                viewModel!.mapController.complete(controller);
                startLocation();
              },
              onCameraMove: (CameraPosition position) {
                viewModel!.getAllNearbyPark(
                    lat: position.target.latitude,
                    lng: position.target.longitude);
              },
            ),

            ///返回键
            Positioned(
              top: MediaQuery
                  .of(context)
                  .padding
                  .top + 28.rpx,
              left: ThemeStyles.pagePaddingHorizontal,
              child: GestureDetector(
                onTap: () {
                  NavigatorUtil.back(context, toRoot: true);
                },
                child: Container(
                  decoration: const BoxDecoration(
                    shape: BoxShape.circle,
                    color: Colors.white,
                  ),
                  width: 50.rpx,
                  height: 50.rpx,
                  child: Icon(
                    Icons.arrow_back_ios_sharp,
                    size: 34.rpx,
                  ),
                ),
              ),
            ),

            /// 底部车辆信息
            Positioned(
                bottom: 0,
                left: 0,
                right: 0,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Padding(
                      padding: EdgeInsets.symmetric(
                          horizontal: ThemeStyles.pagePaddingHorizontal),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: [

                          ///tips
                          _buildTips(S.current.rideSlowlyTips),
                          Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              CircleButtonWidget(
                                path: 'assets/images/location.png',
                                onClick: () {
                                  startLocation();
                                },
                              ),
                              SizedBox(
                                height: 28.rpx,
                              ),
                              CircleButtonWidget(
                                path: 'assets/images/service.png',
                                onClick: () {
                                  NavigatorUtil.push(
                                      context, Routers.questionView);
                                },
                              )
                            ],
                          )
                        ],
                      ),
                    ),
                    _BottomStackWidget(
                      key: infoKey,
                      viewModel: viewModel!,
                    )
                  ],
                ))
          ],
        ));
  }

  Widget _buildTips(String tips) {
    return Container(
        padding: EdgeInsets.only(right: 8.rpx, top: 4.rpx, bottom: 4.rpx),
        decoration: BoxDecoration(
          color: ColorStyles.color_FFF4E0,
          borderRadius: BorderRadius.circular(16.rpx),
          boxShadow: [
            BoxShadow(
              color: ColorStyles.color_CC646464,
              blurRadius: 16.rpx,
              offset: Offset(0, 4.rpx),
            )
          ],
        ),
        child: Row(mainAxisSize: MainAxisSize.min, children: [
          Image.asset(
            'assets/images/ic_tips_ring.png',
            width: 64.rpx,
            height: 64.rpx,
          ),
          SizedBox(
            height: 16.rpx,
          ),
          Text(
            tips,
            style: TextStyle(fontSize: 26.rpx, color: ColorStyles.color_FF5500),
          ),
        ]));
  }
}

enum BikeStatus {
  /// 开锁中
  unLocking,

  /// 开锁成功
  unLockSuccess,

  /// 开锁失败
  unLockFailed,

  /// 骑行中：开锁成功后、从临时锁车恢复骑行后、从其他页面返回
  riding,

  /// 临时锁车确认
  tempLockConfirm,
  /// 临时锁车中
  tempLocking,
  /// 临时锁车成功
  tempLockSuccess,
  /// 临时解锁失败
  tempLockFailed,
  /// 临时锁车倒计时(锁车成功后)
  tempLockCount,

  ///临时锁车解锁车辆确认
  temUnLockConfirm,
  temUnLockSuccess,


  /// 还车中
  backing,
  /// 还车成功
  backSuccess,
  /// 还车失败
  backFailed,

  /// 开头盔确认
  openHelmetConfirm,
  openHelmetFailed,
  openHelmetSuccess,
  openHelmeting,
}

class _BottomStackWidget extends StatefulWidget {
  final CyclingViewModel viewModel;

  const _BottomStackWidget(
      {required this.viewModel,super.key});

  @override
  State<_BottomStackWidget> createState() => _BottomStackWidgetState();
}

class _BottomStackWidgetState extends State<_BottomStackWidget> with SingleTickerProviderStateMixin{
  CyclingViewModel get viewModel => widget.viewModel;
  late Timer timer;
  late AnimationController _animationController;
  int percent = 0;

  Widget _buildStatusWidget(BikeStatus status) {
    switch (status) {
      case BikeStatus.unLocking:
      case BikeStatus.unLockSuccess:
      case BikeStatus.unLockFailed:
        return _buildUnLockResultTemplate(status);
      case BikeStatus.riding:
      case BikeStatus.backFailed:
      case BikeStatus.tempLockCount:
        return _ridingWidget();
      case BikeStatus.temUnLockConfirm:
      case BikeStatus.temUnLockSuccess:
      case BikeStatus.tempLockConfirm:
      case BikeStatus.tempLocking:
      case BikeStatus.tempLockSuccess:
      case BikeStatus.tempLockFailed:
        return _buildTempLockTemplate(status);
      case BikeStatus.backing:
      case BikeStatus.backSuccess:
        return _buildBackResultTemplate(status);
      case BikeStatus.openHelmetConfirm:
      case BikeStatus.openHelmetFailed:
      case BikeStatus.openHelmetSuccess:
      case BikeStatus.openHelmeting:
        return _buildHelmetResultTemplate(status);
    }
  }

  void cancelTimer() {
    timer.cancel();
    _animationController.dispose();
  }

  @override
  void initState() {
    super.initState();
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      viewModel.unLockCountdownTime.value +=1;
      viewModel.tempLockCountdownTime.value +=1;

      if(viewModel.unLockCountdownTime.value % 10 == 0){
        ///间隔10s请求一次订单状态
        viewModel.getOrderNoExist();
      }
      if(viewModel.unLockCountdownTime.value % 60 == 0){
        ///间隔一分钟请求一次车辆信息、区域信息、附近站点信息
        viewModel.getBrandAreaInfo();
        viewModel.getBikeInfo(viewModel.vid!);
        viewModel.getAllNearbyPark(lat: AccountManager.userLatitude!, lng: AccountManager.userLongitude!);
      }
    });

    _animationController = AnimationController(
        vsync: this,
        duration: const Duration(milliseconds: 500),
        animationBehavior:AnimationBehavior.preserve)
      ..addStatusListener((AnimationStatus status) {
        if (status == AnimationStatus.dismissed) {
          _animationController.forward();
        }
      })
      ..addListener(() {
        setState(() {
          //为了动画能不停重复 这里在动画完成时 置初始位置
          if(_animationController.value==1.0){
            if(percent < 90){
              percent += 10;
            }else{
              percent = 99;
            }
            _animationController.value = 0.0;
          }
        });
      });
  }


  @override
  void dispose() {
    timer.cancel();
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width,
      margin: EdgeInsets.only(top: 16.rpx),
      padding: EdgeInsets.all(ThemeStyles.pagePaddingHorizontal),
      decoration: BoxDecoration(
        color: ColorStyles.color_FFFFFF,
        borderRadius: BorderRadius.only(
            topLeft: Radius.circular(16.rpx),
            topRight: Radius.circular(16.rpx)),
        boxShadow: [
          BoxShadow(
            color: ColorStyles.color_CC646464,
            blurRadius: 16.rpx,
            offset: Offset(0, -8.rpx),
          )
        ],
      ),
      child: ValueListenableBuilder(valueListenable: viewModel.bikeStatus,builder: (context,data,_){
        if([BikeStatus.unLocking,BikeStatus.tempLocking,BikeStatus.backing,BikeStatus.openHelmeting].contains(data)){
          if(!_animationController.isAnimating){
            percent = 0;
            _animationController.forward();
          }
        }else{
          if(_animationController.isAnimating){
            _animationController.stop();
          }
        }
        return _buildStatusWidget(data);
      }),
    );
  }

  Widget _buildUnLockResultTemplate(BikeStatus status) {
    return Column(
      children: [
        SizedBox(
          height: 200.rpx,
          child: Stack(
            children: [
              Align(
                alignment: Alignment.bottomCenter,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    if (status == BikeStatus.unLocking)
                      ...[
                        SizedBox(
                          height: 150.rpx,
                          width: 150.rpx,
                          child: Stack(
                            children: [
                              RotationTransition(
                                alignment: Alignment.center,
                                turns: _animationController,
                                child: Image.asset(
                                  'assets/applet/img_rotate.png',
                                  height: 150.rpx,
                                  width: 150.rpx,
                                  fit: BoxFit.cover,
                                ),
                              ),
                              Center(
                                child: Text('$percent%',style: TextStyle(fontSize: 36.rpx,color: ColorStyles.color_333333,fontWeight: FontWeight.w500),),
                              )
                            ],
                          ),
                        ),
                        Text(
                          '${S.current.unlocking}...',
                          style: TextStyles.style_333_16_w500,
                        ),
                      ],

                    if (status == BikeStatus.unLockSuccess)
                      ...[
                        Image.asset(
                          'assets/applet/ic_unlock_success.png',
                          width: 96.rpx,
                          height: 96.rpx,
                        ),
                        Text(
                          S.current.unlockSuccess,
                          style: TextStyles.style_333_16_w500,
                        ),
                      ],

                    if (status == BikeStatus.unLockFailed)
                      ...[
                        Image.asset(
                          'assets/applet/ic_unlock_failed.png',
                          width: 96.rpx,
                          height: 96.rpx,
                        ),
                        Text(
                          viewModel.borrowBikeM?.errorMsg??S.current.unlockFail,
                          style: TextStyles.style_333_16_w500,
                        )
                      ]
                  ],
                ), //动画
              ),
              Align(
                alignment: Alignment.topRight,
                child: XbButton(
                  height: 48.rpx,
                  width: 148.rpx,
                  isDefault: true,
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Image.asset(
                        'assets/applet/ic_fault.png',
                        width: 24.rpx,
                        height: 24.rpx,
                      ),
                      Text(
                        S.current.feedback,
                        style: TextStyles.style_small_btn,
                      ),
                    ],
                  ),
                  onPressed: () {
                    NavigatorUtil.push(context, Routers.faultReportView,arguments: {'vid':viewModel.vid});
                  },
                ),
              ),
            ],
          ),
        ),
        SizedBox(
          height: 20.rpx,
        ),
        if (status == BikeStatus.unLocking)
          Image.asset(
            'assets/applet/img_region03.png',
            height: 200.rpx,
            fit: BoxFit.fitHeight,
          ),
        if (status == BikeStatus.unLockSuccess ||
            status == BikeStatus.unLockFailed)
          Image.asset(
            'assets/applet/img_region02.png',
            height: 200.rpx,
            fit: BoxFit.fitHeight,
          ),
        SizedBox(
          height: 20.rpx,
        ),
        if (status == BikeStatus.unLockFailed)
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(child: XbButton(
                isDefault: false,
                color: ColorStyles.color_EEEEEE,
                onPressed: () {
                  NavigatorUtil.back(context);
                },
                child: Text(
                  S.current.goBack,
                  style: const TextStyle(color: ColorStyles.color_333333),
                ),
              ),),
              SizedBox(
                width: 16.rpx,
              ),
              Expanded(child: XbButton(
                isDefault: false,
                color: ColorStyles.color_1082FF,
                onPressed: () {
                  viewModel.borrowBike(viewModel.vid!);
                },
                child: Text(
                  S.current.reUnlock,
                ),
              ),),
            ],
          )
      ],
    );
  }

  Widget _buildTempLockTemplate(BikeStatus status) {
    return Column(
        children: [
          if(status == BikeStatus.temUnLockSuccess)
            ...[
              _buildContent(title: S.current.unlockBikeSuccess,
                  contentIconPath: 'assets/applet/img_locking_open.png'),
            ],
          if(status == BikeStatus.temUnLockConfirm)
            ...[
              _buildContent(title: S.current.unlockTips,
                  contentIconPath: 'assets/applet/ic_lock_bike.png'),
              Row(
                children: [
                  Expanded(child: XbButton(
                      isDefault: false,
                      color: ColorStyles.color_EEEEEE,
                      onPressed: () {
                        viewModel.bikeStatus.value = BikeStatus.tempLockCount;
                      },
                      child: Text(
                        S.current.cancel,
                        style: const TextStyle(color: ColorStyles.color_333333),
                      )
                  ),),
                  SizedBox(
                    width: 16.rpx,
                  ),
                  Expanded(child: XbButton(
                    isDefault: false,
                    color: ColorStyles.color_1082FF,
                    onPressed: () {
                      viewModel.tempLockBike(
                          viewModel.vid!, viewModel.orderId!,2);
                    },
                    child: Text(
                      S.current.confirm,
                    ),
                  ),),
                ],
              )
            ],
          if(status == BikeStatus.tempLockConfirm)
            ...[
              _buildContent(title: S.current.unlockTempTips,
                  content: '${S.current.unlockTempTips2}${AccountManager.areaInfoM?.temporaryDeviceLockTime}${S.current.mins}，${S.current.unlockTempTips3}',
                  contentIconPath: 'assets/applet/ic_lock_bike.png'),
              Row(
                children: [
                  Expanded(child: XbButton(
                      isDefault: false,
                      color: ColorStyles.color_EEEEEE,
                      onPressed: () {
                        viewModel.bikeStatus.value = BikeStatus.riding;
                      },
                      child: Text(
                        S.current.cancel,
                        style: const TextStyle(color: ColorStyles.color_333333),
                      )
                  ),),
                  SizedBox(
                    width: 16.rpx,
                  ),
                  Expanded(child: XbButton(
                    isDefault: false,
                    color: ColorStyles.color_1082FF,
                    onPressed: () {
                      viewModel.tempLockBike(
                          viewModel.vid!, viewModel.orderId!,1);
                    },
                    child: Text(
                      S.current.confirm,
                    ),
                  ),),
                ],
              )
            ],
          if(status == BikeStatus.tempLocking)
            ...[
              _buildContent(title: '${S.current.unlockTemping}…',
                  content: S.current.unlockTempingTips,
                  contentIconPath: 'assets/applet/img_locking.png',showLoading:true),
            ],
          if(status == BikeStatus.tempLockSuccess)
            ...[
              _buildContent(titleIconPath: 'assets/applet/ic_success.png',
                  title: S.current.unlockTempingSuccess,
                  content: S.current.unlockTempingSuccessTips,
                  contentIconPath: 'assets/applet/img_locking_open.png'),
            ],
          if(status == BikeStatus.tempLockFailed)
            ...[
              _buildContent(titleIconPath: 'assets/applet/ic_fail.png',
                  title: S.current.unlockTempingFail,
                  titleColor: ColorStyles.color_474747,
                  content: viewModel.tempLockBikeM?.statusMessage ??
                      S.current.unlockTempingFailTips,
                  contentIconPath: 'assets/applet/img_locking_fail.png'),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(child: XbButton(
                      isDefault: false,
                      color: ColorStyles.color_EEEEEE,
                      onPressed: () {
                        viewModel.bikeStatus.value = BikeStatus.riding;
                      },
                      child: Text(
                        S.current.goBack,
                        style: const TextStyle(color: ColorStyles.color_333333),
                      )
                  ),),
                  SizedBox(
                    width: 16.rpx,
                  ),
                  Expanded(child: XbButton(
                    isDefault: false,
                    onPressed: () {
                      viewModel.returnBike(
                          viewModel.vid!, viewModel.orderId!);
                    },
                    child: Text(
                      S.current.returnBike,
                    ),
                  ),),
                  SizedBox(
                    width: 16.rpx,
                  ),
                  Expanded(child: XbButton(
                    isDefault: false,
                    color: ColorStyles.color_1082FF,
                    onPressed: () {
                      viewModel.tempLockBike(
                          viewModel.vid!, viewModel.orderId!,1);
                    },
                    child: Text(
                      S.current.reUnlockTemp,
                    ),
                  ),),
                ],
              )
            ]
        ]
    );
  }

  Widget _buildBackResultTemplate(BikeStatus status) {
    if(status == BikeStatus.backing){
      return _buildContent(title: '${S.current.backing}…',titleIconPath: 'assets/applet/ic_success.png',
          content: S.current.backingTips,
          contentIconPath: 'assets/applet/img_locking.png',showLoading:true);
    }else if(status == BikeStatus.backSuccess){
      return _buildContent(title: S.current.backingSuccess,
          content: S.current.backingSuccessTips,
          contentIconPath: 'assets/applet/img_region03.png');
    }
    throw Exception('unknown status $status');
  }

  Widget _buildHelmetResultTemplate(BikeStatus status) {
    return Column(
      children: [
        if(status == BikeStatus.openHelmetConfirm)
          ...[
            _buildContent(title: S.current.openHelmet,
                content: S.current.openHelmetTips,
                contentIconPath: 'assets/applet/img_helmet.png',showContentIconBg: true),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(child: XbButton(
                    isDefault: false,
                    color: ColorStyles.color_EEEEEE,
                    onPressed: () {
                      viewModel.bikeStatus.value = BikeStatus.riding;
                    },
                    child: Text(
                      S.current.cancel,
                      style: const TextStyle(color: ColorStyles.color_333333),
                    )
                ),),
                SizedBox(
                  width: 16.rpx,
                ),
                Expanded(child: XbButton(
                  isDefault: false,
                  color: ColorStyles.color_1082FF,
                  onPressed: () {
                    viewModel.helmetUnlock(viewModel.vid!, viewModel.orderId!);
                  },
                  child: Text(
                    S.current.openHelmetConfirm,
                  ),
                ),),
              ]
            )
          ],
        if(status == BikeStatus.openHelmeting)
          ...[
            _buildContent(title: '${S.current.openHelmeting}…',
                content: S.current.openHelmetingTips,
                contentIconPath: 'assets/applet/img_helmeting.png',showContentIconBg: true),
          ],
        if(status == BikeStatus.openHelmetSuccess)
          ...[
            _buildContent(title: S.current.openHelmeted,titleIconPath: 'assets/applet/ic_success.png',
                content: S.current.openHelmetedTips,
                contentIconPath: 'assets/applet/img_helmet_success.png',showContentIconBg: true),
            Row(
              children: [
                Expanded(child: XbButton(
                  isDefault: false,
                  color: ColorStyles.color_1082FF,
                  onPressed: () {
                    viewModel.bikeStatus.value = BikeStatus.riding;
                  },
                  child: Text(
                    S.current.known,
                  ),
                ),)
              ],
            ),
          ],
        if(status == BikeStatus.openHelmetFailed)
          ...[
            _buildContent(title: S.current.openHelmetFail,titleIconPath: 'assets/applet/ic_fail.png',
                content: viewModel.helmetUnlockM?.statusMessage??S.current.openHelmetFailTips,
                contentIconPath: 'assets/applet/img_helmet_failed.png',showContentIconBg: true),
            Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(child: XbButton(
                      isDefault: false,
                      color: ColorStyles.color_EEEEEE,
                      onPressed: () {
                        viewModel.bikeStatus.value = BikeStatus.riding;
                      },
                      child: Text(
                        S.current.goBack,
                        style: TextStyle(color: ColorStyles.color_333333),
                      )
                  ),),
                  SizedBox(
                    width: 16.rpx,
                  ),
                  Expanded(child: XbButton(
                    isDefault: false,
                    color: ColorStyles.color_BDE7FF,
                    onPressed: () {
                      //todo 如果有进行中的订单 怎么换一辆车
                    },
                    child: Text(
                      S.current.otherBike,
                    ),
                  ),),
                  SizedBox(
                    width: 16.rpx,
                  ),
                  Expanded(child: XbButton(
                    isDefault: false,
                    color: ColorStyles.color_1082FF,
                    onPressed: () {
                      viewModel.helmetUnlock(viewModel.vid!, viewModel.orderId!);
                    },
                    child: Text(
                      S.current.reUnlock,
                    ),
                  ),),
                ]
            )
          ],
      ],
    );
  }

  Widget _ridingWidget() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  margin: EdgeInsets.only(right: 28.rpx),
                  padding: EdgeInsets.only(left: 8.rpx),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8.rpx),
                    gradient: const LinearGradient(
                      colors: [
                        ColorStyles.color_EEEEEE,
                        ColorStyles.color_FFFFFF
                      ],
                    ),
                  ),
                  child: Text('No.${viewModel.bikeInfoM?.bikeInfo?.id??'-'}'),
                ),
                if (viewModel.bikeInfoM?.bikeInfo?.id != null)
                  GestureDetector(
                    onTap: () {
                      Clipboard.setData(ClipboardData(
                          text: viewModel.bikeInfoM!.bikeInfo!.id!));
                      EasyLoading.showSuccess(S.current.copySuccess);
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(horizontal: 4.rpx),
                      decoration: BoxDecoration(
                        border: Border.all(
                            color: ColorStyles.color_EEEEEE, width: 1),
                        borderRadius: BorderRadius.circular(8.rpx),
                      ),
                      child: Text(
                        S.current.copy,
                        style: TextStyle(
                            fontSize: 24.rpx, color: ColorStyles.color_999999),
                      ),
                    ),
                  )
              ],
            ),
            XbButton(
              height: 48.rpx,
              width: 120.rpx,
              isDefault: false,
              color: const Color(0xFFE6F7FF),
              borderRadius: BorderRadius.all(Radius.circular(24.rpx)),
              padding:
              EdgeInsets.symmetric(horizontal: 12.rpx, vertical: 4.rpx),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Image.asset(
                    'assets/images/ico_ring.png',
                    width: 32.rpx,
                    height: 32.rpx,
                  ),
                  Text(
                    S.current.searchCarRing,
                    style: TextStyle(
                      color: ColorStyles.color_1082FF,
                      fontSize: 26.rpx,
                    ),
                  ),
                ],
              ),
              onPressed: () {
                viewModel.findBike(viewModel.vid!);
              },
            ),
          ],
        ),
        SizedBox(
          height: 26.rpx,
        ),

        /// 骑行时长、费用
        ValueListenableBuilder(valueListenable: viewModel.unLockCountdownTime,builder: (context,data,_){
          return Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Flexible(child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    S.current.rideTime,
                    style:
                    TextStyle(fontSize: 26.rpx, color: ColorStyles.color_999999),
                  ),
                  Text(
                    durationTransform(data.toInt()),
                    style: TextStyle(
                        fontSize: 50.rpx,
                        color: ColorStyles.color_333333,
                        fontWeight: FontWeight.w500),
                  ),
                ],
              )),
              if (viewModel.unPayInfoM?.rideStatus == 5)
                Flexible(child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Flexible(child: Text(
                      S.current.tempLocked,
                      style: TextStyle(
                          fontSize: 26.rpx, color: ColorStyles.color_1082FF),
                    )),
                    ValueListenableBuilder(valueListenable: viewModel.tempLockCountdownTime, builder: (context,data,_){
                      return Text(
                        durationTransform(data.toInt(),),
                        style: TextStyle(
                            fontSize: 50.rpx,
                            color: ColorStyles.color_1082FF,
                            fontWeight: FontWeight.w500),
                      );
                    }),
                  ],
                )),
              Flexible(child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  GestureDetector(
                    onTap: () {
                      NavigatorUtil.push(context, Routers.freightView);
                    },
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text(
                          S.current.ridingFee,
                          style: TextStyle(
                              fontSize: 26.rpx, color: ColorStyles.color_999999),
                        ),
                        Icon(
                          Icons.help_outline_rounded,
                          color: ColorStyles.color_999999,
                          size: 32.rpx,
                        )
                      ],
                    ),
                  ),
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        viewModel.unPayInfoM == null
                            ? '0'
                            : '${computeAmount(viewModel.unPayInfoM!, viewModel.unLockCountdownTime.value, viewModel.bikeInfoM?.feeInfo, AccountManager.areaInfoM!)}',
                        style: TextStyle(
                            fontSize: 50.rpx,
                            color: ColorStyles.color_333333,
                            fontWeight: FontWeight.w500),
                      ),
                      Text(
                        S.current.yuan,
                        style: TextStyle(
                            fontSize: 26.rpx, color: ColorStyles.color_333333),
                      )
                    ],
                  )
                ],
              ))
            ],
          );
        },),
        SizedBox(
          height: 16.rpx,
        ),

        ///车辆骑行状态
        Builder(builder: (context) {
          final good = viewModel.bikeInfoM?.bikeUseStatus?.isSocFix == 1;

          return Row(
            children: [
              Image.asset(
                'assets/images/${good ? 'ic_battery' : 'ico_low_battery'}.png',
                width: 32.rpx,
                height: 32.rpx,
              ),
              Text(
                good ? S.current.goodPower : S.current.badPower,
                style: TextStyle(
                    color: good
                        ? const Color(0xff09AB7A)
                        : ColorStyles.color_FF4D00,
                    fontSize: 26.rpx),
              ),
              Container(
                width: 1,
                height: 36.rpx,
                color: ColorStyles.color_EEEEEE,
                margin: const EdgeInsets.symmetric(horizontal: 4),
              ),
              Text(
                '${S.current.expectedRideTo}${viewModel.bikeInfoM?.bikeUseStatus?.riddingMile ??
                    0}km',
                style: TextStyle(
                    fontSize: 26.rpx, color: ColorStyles.color_666666),
              )
            ],
          );
        }),
        SizedBox(
          height: 24.rpx,
        ),

        ///帮助列
        Row(
          children: [
            _buildHelpItem(S.current.chargeStandard, () {
              NavigatorUtil.push(context, Routers.freightView);
            }),
            if(AccountManager.areaInfoM?.isForceHelmet == 1 || (AccountManager.areaInfoM?.isNeedHelmet != 2 && viewModel.unPayInfoM?.helmetReact == 1))
              _buildHelpItem(S.current.howReturnHelmet, () {
                NavigatorUtil.push(context, Routers.webViewPage,arguments: {'url':'${AccountManager.baseUrl}/helmet_rule.html'});
              }),
            if(viewModel.bikeRealTimeM?.isSupportBeacon == 1)
              _buildHelpItem(S.current.howReturnBike, () {
                NavigatorUtil.push(context, Routers.webViewPage,arguments: {'url':'${AccountManager.baseUrl}/bluetooth_rule.html'});
              }),
            if(viewModel.bikeRealTimeM?.isSupportRfid == 1)
              _buildHelpItem(S.current.howReturnBike, () {
                NavigatorUtil.push(context, Routers.webViewPage,arguments: {'url':'${AccountManager.baseUrl}/rfid_rule.html'});
              }),
            _buildHelpItem(S.current.feedback, () {
              NavigatorUtil.push(context, Routers.faultReportView,arguments: {'vid':viewModel.vid});
            }),
          ],
        ),
        SizedBox(
          height: 24.rpx,
        ),

        /// 归还车辆
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            ...viewModel.unPayInfoM?.rideStatus == 5?
              [
                Expanded(child: XbButton(
                  padding: EdgeInsets.zero,
                  isDefault: false,
                  color: ColorStyles.color_388E3C,
                  child: Text(S.current.unlockBike.fixAutoLines(),),
                  onPressed: () {
                    viewModel.bikeStatus.value = BikeStatus.temUnLockConfirm;
                  },
                ),),
                SizedBox(width: 12.rpx,),
              ]:[
              Expanded(child: XbButton(
                padding: EdgeInsets.zero,
                isDefault: false,
                color: ColorStyles.color_999999,
                child: Text(S.current.unlockTemp.fixAutoLines(),style: TextStyle(fontSize: 30.rpx),),
                onPressed: () {
                  viewModel.bikeStatus.value = BikeStatus.tempLockConfirm;
                },
              ),),
              SizedBox(width: 12.rpx,),
            ],
            Expanded(child: XbButton(
              padding: EdgeInsets.zero,
              isDefault: false,
              child: Text(S.current.openHelmetTo.fixAutoLines()),
              onPressed: () {
                viewModel.bikeStatus.value = BikeStatus.openHelmetConfirm;
              },
            ),),
            SizedBox(width: 12.rpx,),
            Expanded(child: XbButton(
              padding: EdgeInsets.zero,
              isDefault: false,
              child: Text(S.current.returnBike.fixAutoLines()),
              onPressed: () {
                showDialog(
                  context: context,
                  barrierDismissible: false,
                  builder: (context) {
                    return MyDialog(
                      title: S.current.returnTo,
                      content: Text(S.current.returnToTips,style: TextStyles.style_small_tips,),
                      onConfirm: () {
                        Navigator.of(context).pop();
                        viewModel.returnBike(viewModel.vid!, viewModel.orderId!);
                      },
                    );
                  },
                );
              },
            ),),
          ],
        )
      ],
    );
  }

  /////////////////////////////////////////////////////////////////
  Widget _buildHelpItem(String text, Function() onPress) {
    return GestureDetector(
      onTap: onPress,
      child: Container(
        padding: EdgeInsets.only(
            right: 16.rpx, left: 16.rpx, top: 8.rpx, bottom: 8.rpx),
        margin: EdgeInsets.only(right: 8.rpx),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8.rpx),
          border: Border.all(color: ColorStyles.color_EEEEEE),
        ),
        child: Text(text,
            style:
            TextStyle(fontSize: 24.rpx, color: ColorStyles.color_999999)),
      ),
    );
  }

  ///[showLoading]是否显示旋转图片
  Widget _buildContent({String? titleIconPath,
    String? title,
    Color? titleColor = ColorStyles.color_333333,
    String? content,
    String? contentIconPath,
    bool showContentIconBg = false,
    bool showLoading = false,
  }) {
    return Column(
      children: [
        Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            if (titleIconPath != null)
              Image.asset(
                titleIconPath,
                width: 40.rpx,
                height: 40.rpx,
              ),
            if (titleIconPath != null)
              SizedBox(
                width: 8.rpx,
              ),
            Text(
              title ?? '',
              style: TextStyles.style_333_16_w500,
            ),
          ],
        ),
        Padding(
          padding: const EdgeInsets.only(left: 18,right: 18,top: 4,bottom: 26),
          child: Text(
            content ?? '',
            style: TextStyle(fontSize: 28.rpx, color: ColorStyles.color_666666),
            textAlign: TextAlign.center,
          ),
        ),

        if(showContentIconBg && contentIconPath != null)
          ///绘制背景和图片
          Container(
            height: 200.rpx,
            decoration: BoxDecoration(
              color: const Color(0xFFF2FBFF),
              borderRadius: BorderRadius.all(Radius.circular(16.rpx))
            ),
            child: Stack(
              children: [
                Center(
                  child: Image.asset(
                    contentIconPath,
                    height: 200.rpx,
                    fit: BoxFit.cover,
                  ),
                ),
              ],
            ),
          ),
        if (!showContentIconBg && contentIconPath != null)
          SizedBox(height: 200.rpx,child: Stack(
            children: [
              Center(
                child: Image.asset(
                  contentIconPath,
                  height: 200.rpx,
                  fit: BoxFit.cover,
                ),
              ),

              if(showLoading)
                Center(
                  child: RotationTransition(
                    alignment: Alignment.center,
                    turns: _animationController,
                    child: Image.asset(
                      'assets/applet/img_rotate.png',
                      height: 150.rpx,
                      width: 150.rpx,
                      fit: BoxFit.cover,
                    ),
                  ),
                )
            ],
          ),),
        SizedBox(height: 26.rpx,),
      ],
    );
  }
}


Map<String,dynamic>? currentTimeInfo;
/// 对骑行中订单进行价格计算  时间为秒
num computeAmount(UnPayInfoM orderInfo, num second, FeeInfo? freeInfo, AreaInfoM serverAreaInfo) {
  var everyMin = (freeInfo?.everyMin??0) * 60; // 计费周期 (分钟)
  var everyPrice = freeInfo?.everyPrice??0;// 每个计费周期的费用
  var freeTime = freeInfo?.freeTime??0;// 免费时长（分钟）
  var startMin = freeInfo?.startMin??0;// 开始计费时间 （分钟）
  var startPrice = freeInfo?.startPrice??0;// 起始价格
  var freeTimeSec = freeInfo?.useFreeTimeSec == 1 ? (freeInfo?.freeTimeSec??0) : freeTime * 60;// freeTimeSec:免费时长（秒）,useFreeTimeSec:是否启用免费时长秒(1:是，2:否)
  var startMinSec = startMin * 60;
  var excludeFreeTime = serverAreaInfo.configs?.excludeFreeTime ?? '2';// 骑行时长是否需排除免费时长
  // 根据订单中的今日已骑行次数和品牌区域接口中的每日免费次数判断，是否这一单可以使用免费时长
  if (serverAreaInfo.freeRidingTimesEveryDay > 0 &&
      orderInfo.dailyRidingTimes! >= serverAreaInfo.freeRidingTimesEveryDay) {
    freeTimeSec = 0;
  }
  // 开启了特殊计费
  if (serverAreaInfo.isBillingDuration == 1 || serverAreaInfo.isBillingDuration == 3) {
    void handleCost() {
      startPrice = currentTimeInfo!['start_price'] ?? startPrice;
      startMinSec = currentTimeInfo!['start_second'] ?? startMinSec;
      everyMin = currentTimeInfo!['billing_duration'] ?? everyMin;
      everyPrice = currentTimeInfo!['billing_price'] ?? everyPrice;
    }

    if (currentTimeInfo != null) {
      handleCost();
    } else {
      List<dynamic> priceInfo = [];
      Map<String, dynamic> weekendPriceInfo = {'display': []};

      try {
        priceInfo = jsonDecode((serverAreaInfo.priceTime == null || serverAreaInfo.priceTime!.isEmpty)? '[]' : serverAreaInfo.priceTime!);
        weekendPriceInfo = jsonDecode((serverAreaInfo.weekPriceTime == null || serverAreaInfo.weekPriceTime!.isEmpty)?'{"display": []}':serverAreaInfo.weekPriceTime!);
      } catch (error) {
        priceInfo = [];
        weekendPriceInfo = {'display': []};
      }

      if (serverAreaInfo.isBillingDuration == 1) {
        // 开启分时段计费
        final date = DateFormat('yyyy/MM/dd ').format(DateTime.fromMillisecondsSinceEpoch(orderInfo.startTime!.toInt() * 1000));
        currentTimeInfo = priceInfo.firstWhere(
              (li) => DateTime.now().isAfter(DateFormat('yyyy/MM/dd HH:mm:ss').parse('$date${li['billing_start_time']}')) &&
                  DateTime.now().isBefore(DateFormat('yyyy/MM/dd HH:mm:ss').parse('$date${li['billing_end_time']}')),
          orElse: () => {},
        );
      } else if (serverAreaInfo.isBillingDuration == 3) {
        // 开启工作日周末计费

        // DateTime.weekday 返回的是1（星期一）到7（星期日）。
        final dayOfWeek = DateTime.fromMillisecondsSinceEpoch(orderInfo.startTime!.toInt() * 1000).weekday;
        // 减去1后，返回值变为0（星期一）到6（星期日）。
        // 加上7并取模7，确保0（星期一）变为1，6（星期日）变为0。
        final adjustedDayOfWeek = (dayOfWeek -1 + 7) % 7;
        currentTimeInfo = (weekendPriceInfo['display'] as List) .firstWhere(
              (li) => li['week_day'].contains(adjustedDayOfWeek),
          orElse: () => {},
        );
      }

      if (currentTimeInfo != null) {
        handleCost();
      }
    }
  }

  // 每分钟字段为0时，分母为0，会出错
  if (everyMin <= 0) {
    return 0;
  }
  // 免费时长内
  if (second <= freeTimeSec) {
    return 0;
  }

  // 骑行时长是否需排除免费时长
  if (excludeFreeTime == '1') {
    second -= freeTimeSec;
  }

  if (second <= startMinSec) {
    return startPrice;
  } else {
    final minNum = (second - startMinSec) / everyMin;
    final amount = startPrice + (minNum.toInt()) * everyPrice;
    return (amount* 100).round() / 100;//保留两位小数
  }
}

